class InvalidUrlError < Exception
  
end

class NoNeedAnalyzingError < Exception
  
end

class Debug
  class << self
    def print_error(e)
      puts e.class.to_s, e.message, e.backtrace
      exit
    end
    
    def on_windows?
      Config::CONFIG['host_os'] == "minw32" ? true : false
    end
  end
end

class VeryCDPage
  def initialize(url)
    @url = url
    @doc = Nokogiri::HTML(open(@url))
    @threads = []
    @links = []
  end
  
  def analyze
    begin 
      before_analyzing
      start_analyzing
      after_analyzing
    rescue Exception => e
      Debug.print_error e
    end
    puts "Costing time: #{@time_end - @time_start}s ..."
  end
  
  protected
  
  def topic_url?
    VeryCDAnalyzeJob::VALID_VERYCD_URL_REGEXP[:topic_url] =~ @url
  end
  
  def entry_url?
    VeryCDAnalyzeJob::VALID_VERYCD_URL_REGEXP[:entry_url] =~ @url
  end
  
  def has_search_button?
    if topic_url?
      @doc.css("a#search_download_icon").empty? ? false : true
    elsif entry_url?
      @doc.css("a#down_button").empty? ? false : true
    else
      false
    end
  end
  
  def before_analyzing
    raise NoNeedAnalyzingError, "You can download ed2k resources from the url, no need for analyzing!" if not has_search_button?
    puts "Now analyzing verycd url #{@url} ..."
    @time_start = Time.now
  end
  
  def start_analyzing
    if topic_url?
      process_for_topic
    elsif entry_url?
      process_for_entry
    end
    write_file
  end
  
  def after_analyzing
    @time_end = Time.now
    puts "Analyzing verycd url #{@url} ends ..."
  end
  
  def process_for_topic
    @link_count = @doc.css("div.emulemain td a").size - 1
    @next_page = Nokogiri::HTML(open(@doc.css("div.emulemain td a").last.attr("href").to_s))
    @next_page.css("#file-results tr td:eq(1) a")[0, @link_count].each do |a|
      @threads << Thread.new do 
        @links << Nokogiri::HTML(open(a.attr("href"))).css("input.downloadButton").attr("name").to_s
      end
    end
    @threads.each { |t| t.join }
  end
  
  def process_for_entry
    puts "no need for this ..."
    #@next_page = Nokogiri::HTML(open(@doc.css("div#entry_button a#down_button"))).attr("href").to_s
  end
  
  def write_file
    @filename = /\d+\/$/.match(@url).to_s.sub(/\//, "") + ".txt"
    open(@filename, "wb") { |f| f.write(@links.join(Debug::on_windows? ? "\r\n" : "\n")) }
  end
end